package com.example.demoweb.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Component;

@Component
@ServletComponentScan
@WebFilter(filterName="apiFilter",urlPatterns= {"/api/*","/test/*"})
public class ApiFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("==================init方法================");
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("==================过滤器回调函数================");
		HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession();
        session.setAttribute("username", "test");
	    //因为登录后保存了username，所以可以先检查username判断是否登录
	    if(session.getAttribute("username")!=null){
	    	chain.doFilter(httpRequest, httpResponse);//已登录，则放行，
	    	return;
	    }else{
	    	httpResponse.setCharacterEncoding("UTF-8");
	        httpResponse.setContentType("application/json; charset=utf-8");
	        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
	        String msg="{\"msg\":\"权限失效,重新授权\",\"status\":\"401\"}";
	        httpResponse.getWriter().write(msg);
	        return;
	    }
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

}
